package com.dycong.common.common.email;

import com.dycong.common.common.StringUtil;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Arrays;
import java.util.Collection;
import java.util.Properties;

/**
 * Created by yu on 15-5-29.
 */
public class EmailUtil {

    static Session mailSession;

    public static void init() {
        if (mailSession == null) {
            synchronized (EmailUtil.class) {
                if (mailSession == null) {
                    Authenticator auth = new SMTPAuthenticator();
                    Properties props = new Properties();
                    props.put("mail.transport.protocol", "smtp");
                    props.put("mail.smtp.host", EmailConfig.getSmtpServer());
                    props.put("mail.smtp.auth", "true");
                    if (StringUtil.isNotEmpty(EmailConfig.getProxyHost(),EmailConfig.getProxyPort())){
                        props.put("mail.smtp.socks.host",EmailConfig.getProxyHost());
                        props.put("mail.smtp.socks.port",EmailConfig.getProxyPort());
                    }
                    mailSession = Session.getDefaultInstance(props, auth);
                }
            }
        }
    }

    public static void sendEmail(String subject, String content, String... toUsers) {
        sendEmail(subject, content, Arrays.asList(toUsers), null, null);
    }

    /**
     *
     * @param subject 主题
     * @param content 内容
     * @param toList 收件人列表
     * @param ccList 抄送列表
     * @param bccList 密送列表
     */
    public static void sendEmail(String subject, String content, Collection<String> toList, Collection<String> ccList, Collection<String> bccList) {
        getMailSession();
        try {
            MimeMessage message = new MimeMessage(mailSession);
            message.setSubject(subject,EmailConfig.getEncoding());
            message.setContent(content, "text/html;charset=" + EmailConfig.getEncoding());
            message.setFrom(new InternetAddress(EmailConfig.getFrom()));
            toList.forEach(to -> addRecipients(message, Message.RecipientType.TO, to));
            if (ccList != null) ccList.forEach(cc -> addRecipients(message, Message.RecipientType.CC, cc));
            if (bccList != null) bccList.forEach(bcc -> addRecipients(message, Message.RecipientType.BCC, bcc));
            Transport.send(message);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Session getMailSession() {
        init();
        return mailSession;
    }

    private static void addRecipients(MimeMessage message, Message.RecipientType type, String recipient) {
        try {
            message.addRecipients(type, recipient);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }


    private static class SMTPAuthenticator extends Authenticator {
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(EmailConfig.getUsername(), EmailConfig.getPassword());
        }
    }


}
